/**
 * Created with IntelliJ IDEA.
 * Description: leetcode: 876. 链表的中间结点
 * <a href="https://leetcode.cn/problems/middle-of-the-linked-list/">...</a>
 * User: DELL
 * Date: 2023-10-10
 * Time: 9:18
 */
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    /**
     * 解题思路: (快慢指针)
     * 定义一个快指针和一个慢指针,快指针每次走两个结点,慢指针每次
     * 走一个结点,这样当快指针走到结尾的时候,慢指针即在中间结点
     *
     * @param head
     * @return
     */
    public ListNode middleNode(ListNode head) {
        // 判空处理
        if (head == null) {
            return null;
        }
        // 利用快慢指针寻找中间结点
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}
